package com.liwen.service.pool;

import org.apache.commons.io.IOUtils;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: li.rui
 * @time: 2018-05-23 17:06
 * @description:
 */
public abstract class PooledFtpClient extends AbstractFtpClient {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    private GenericObjectPool<SessionObj> pool;

    /**
     * 构造方法
     *
     * @param host
     * @param user
     * @param pwd
     * @param port
     * @param maxTotal
     * @param maxIdle
     * @param maxIdleSeconds
     */
    public PooledFtpClient(String host, String user, String pwd, int port, String certPath, int maxTotal, int maxIdle, int maxIdleSeconds) {
        super(host, user, pwd, port);
        try {
            SessionPoolFactory factory = new SessionPoolFactory(this, maxIdleSeconds * 1000);
            pool = new GenericObjectPool<>(factory);
            pool.setMaxTotal(maxTotal);
            pool.setMaxIdle(maxIdle);
            pool.setTestOnBorrow(true);
            pool.setTestWhileIdle(true);
            pool.setTestOnReturn(true);
        } catch (Exception e) {
            log.error("init-err=err:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 从连接池获取连接
     *
     * @return
     * @throws Exception
     */
    public SessionObj borrowObj() throws Exception {
        return pool.borrowObject();
    }

    /**
     * 归还连接
     *
     * @param obj
     * @throws Exception
     */
    public void returnObj(SessionObj obj) {
        if (null != obj)
            pool.returnObject(obj);
    }

    /**
     * 下载文件
     *
     * @param remotePath 远程文件路径
     * @return
     */
    @Override
    public byte[] download(String remotePath) {
        SessionObj obj = null;
        try {
            obj = borrowObj();
            InputStream is = obj.getSftp().get(remotePath);
            return afterDownload(IOUtils.toByteArray(is));
        } catch (Exception e) {
            log.error("download-err=remotePath:{},msg:{}", remotePath, e.getMessage());
            return null;
        } finally {
            returnObj(obj);
        }
    }

    /**
     * 批量下载
     *
     * @param remotePaths
     * @return
     */
    @Override
    public List<byte[]> download(List<String> remotePaths) {
        SessionObj obj = null;
        try {
            obj = borrowObj();
            List<byte[]> list = new ArrayList<>();
            for (String remotePath : remotePaths) {
                InputStream is = obj.getSftp().get(remotePath);
                list.add(afterDownload(IOUtils.toByteArray(is)));
            }
            return list;
        } catch (Exception e) {
            log.error("download-err=remotePath:{},msg:{}", remotePaths, e.getMessage());
            return null;
        } finally {
            returnObj(obj);
        }
    }

}
